/**
  ******************************************************************************
  * @file    cfbsp.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "bsp.h"
#include "cf.h"
#include "tskcfg.h"

volatile uint32_t Cf_TimerTick = 0;

void Cf_BspInit(void)
{
  LL_TIM_InitTypeDef TIM_InitStruct = {0};
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  
  /* Peripheral clock enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM6);

  /* TIM6 interrupt Init */
  NVIC_SetPriority(TIM6_IRQn, 3);
  NVIC_EnableIRQ(TIM6_IRQn);
  /* EXTI interrupt init*/
  NVIC_SetPriority(EXTI4_15_IRQn, 3);
  NVIC_EnableIRQ(EXTI4_15_IRQn);
  
  /*Configure GPIO pin : PtPin */
  GPIO_InitStruct.Pin  = IN01_Pin|IN02_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  
  TIM_InitStruct.Prescaler   = 64000-1;
  TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
  TIM_InitStruct.Autoreload  = 1000;
  LL_TIM_Init(TIM6, &TIM_InitStruct);
	
  LL_TIM_EnableARRPreload(TIM6);
	
  LL_TIM_SetTriggerOutput(TIM6, LL_TIM_TRGO_RESET);
	
	LL_TIM_SetOnePulseMode(TIM6, LL_TIM_ONEPULSEMODE_REPETITIVE);
	
  LL_TIM_DisableMasterSlaveMode(TIM6);
	
	LL_TIM_EnableIT_UPDATE(TIM6);
	
  TIM6->CR1 &= ~TIM_CR1_CEN;
}

void EXTI4_15_IRQHandler(void)
{
	if(__HAL_GPIO_EXTI_GET_IT(IN01_Pin) != RESET)
  {
    __HAL_GPIO_EXTI_CLEAR_IT(IN01_Pin);
		
		if(Cf_InDetect_Shd != NULL)
		{
			xSemaphoreGiveFromISR(Cf_InDetect_Shd, NULL);
		}
	}
	
	if(__HAL_GPIO_EXTI_GET_IT(IN02_Pin) != RESET)
  {
    __HAL_GPIO_EXTI_CLEAR_IT(IN02_Pin);
		
		if(Cf_InDetect_Shd != NULL)
		{
			xSemaphoreGiveFromISR(Cf_InDetect_Shd, NULL);
		}
	}
}

void TIM6_IRQHandler(void)
{
	if(LL_TIM_IsActiveFlag_UPDATE(TIM6) != 0)
	{
		LL_TIM_ClearFlag_UPDATE(TIM6);
    
    if((Cf_State.cfkg_st == 1) && (Cf_RunPara.cfot != 0))
    {
      Cf_TimerTick++;
      
      if(Cf_TimerTick > Cf_RunPara.cfot)
      {
        xQueueSendFromISR(Cf_RxCmd_Qhd, &Cf_SendCmdOff, NULL);
        
        if(Cf_TimerTick >= Cf_RunPara.cfot+5)
        {
          Cf_TimerTick = 0;
        }
      }
    }
    else
    {
      Cf_TimerTick = 0;
    }
	}
}
